package com.hcg.multiplydatasourceofanno.config.datasource;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;

/**
 * 多数据源，切面处理类 处理带有注解的方法类
 */
@Aspect
@Component
@Slf4j
public class DataSourceAspect implements Ordered {

    //注意：这里的xxxx代表的是上面public @interface DataSource这个注解DataSource的包名
    @Pointcut("@annotation(com.hcg.multiplydatasourceofanno.config.datasource.MultiDataSource)")
    public void dataSourcePointCut() {

    }

    @Around("dataSourcePointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        MultiDataSource ds = method.getAnnotation(MultiDataSource.class);
        if (ds == null) {
            AnnoDynamicDataSource.setDataSource(DataSourceNames.HCG);
            log.info("set datasource is " + DataSourceNames.HCG);
        } else {
            AnnoDynamicDataSource.setDataSource(ds.name());
            log.debug("set datasource is " + ds.name());
        }
        try {
            return point.proceed();
        } finally {
            AnnoDynamicDataSource.clearDataSource();
            log.debug("clean datasource");
        }
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
